package com.cloudcc.mobile.view.schedule;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.cloudcc.cloudframe.util.DateUtils;
import com.cloudcc.mobile.R;
import com.cloudcc.mobile.manager.RunTimeManager;
import com.cloudcc.mobile.manager.UrlManager;
import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.litesuits.android.log.Log;
import com.mypage.bean.SuccessBean;
import com.mypage.utils.UtilsShowDialog;
import com.mypage.view.activity.AtContaxtActivity_;
import com.mypage.view.datedialog.DateTimeUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class NewEventActivity extends Activity implements OnClickListener {
	private TextView bar_title_text;
	private Button mBtnBack;// 返回按钮
	private EditText zhutieditText;// 主题
	private Button beifenpeireneditText;// 被分配人
	private Button zhuangtaieditText;// 状态
	private Button xiangguanxiangeditText;// 相关项
	private RelativeLayout dataLayout;// 这是日期时间的点击时间
	private EditText beizhuedit;
	private Button newtaskbtn;
	private Button mTime;
	private Button btnData;
	private int mPerson = 1;
	private int mStateCode = 2;
	private String userId;
	private UtilsShowDialog showDialog;
	private String mDatime;
	private String mXgx;
	private String mEns = RunTimeManager.getInstance().getlanguage();
	private String stateString;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.newevent);
		mDatime = getIntent().getStringExtra("clickTime");
		showDialog = new UtilsShowDialog(this);
		bar_title_text = (TextView) findViewById(R.id.bar_title_text);
if ("en".equals(mEns)) {
			bar_title_text.setText("New Event");
		}else{
			bar_title_text.setText("新建事件");
		}

		mBtnBack = (Button) findViewById(R.id.mBtnBack);// 返回按钮
		zhutieditText = (EditText) findViewById(R.id.zhutieditText);// 主题
		beifenpeireneditText = (Button) findViewById(R.id.beifenpeireneditText);// 被分配人
		zhuangtaieditText = (Button) findViewById(R.id.zhuangtaieditText);// 状态
		xiangguanxiangeditText = (Button) findViewById(R.id.xiangguanxiangeditText);// 相关项
		dataLayout = (RelativeLayout) findViewById(R.id.dataLayout);
		beizhuedit = (EditText) findViewById(R.id.beizhuedit);
		newtaskbtn = (Button) findViewById(R.id.newtaskbtn);
		mTime = (Button) findViewById(R.id.daoqiriqieditText);
		btnData = (Button) findViewById(R.id.btnData);
		setTimeStr();
		mBtnBack.setOnClickListener(this);
		zhutieditText.setOnClickListener(this);
		beifenpeireneditText.setOnClickListener(this);
		zhuangtaieditText.setOnClickListener(this);
		xiangguanxiangeditText.setOnClickListener(this);
		dataLayout.setOnClickListener(this);
		beizhuedit.setOnClickListener(this);
		newtaskbtn.setOnClickListener(this);
		mTime.setOnClickListener(this);
		btnData.setOnClickListener(this);

	}

	public void setTimeStr() {

		Calendar starts = Calendar.getInstance();
		int crrentHour = starts.get(Calendar.HOUR);
		if (!"".equals(mDatime)) {
			starts.setTime(DateUtils.stringToDate(mDatime, "yyyy-MM-dd HH:mm:ss"));
			starts.set(Calendar.HOUR, crrentHour);
		}
		starts.set(Calendar.MINUTE, 0);
		starts.set(Calendar.SECOND, 0);
		starts.add(Calendar.HOUR, 1);
		mTime.setText(DateUtils.dateToString(starts.getTime(),
				"yyyy-MM-dd HH:mm:ss"));
		starts.add(Calendar.HOUR, 1);
		btnData.setText(DateUtils.dateToString(starts.getTime(),
				"yyyy-MM-dd HH:mm:ss"));
		userId = RunTimeManager.getInstance().getUserId();
if ("en".equals(mEns)) {
	beifenpeireneditText.setText("Own oneself");
		}else{
			beifenpeireneditText.setText("自己");
		}

	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		final Button daoqiriqieditText = (Button) findViewById(R.id.daoqiriqieditText);// 到期日期
		switch (v.getId()) {
		// 返回
		case R.id.mBtnBack:
			finish();
			break;
		// 主题
		case R.id.zhutieditText:

			break;
		// 被分配人
		case R.id.beifenpeireneditText:
			setFenPeiActivity();
			break;
		// 类型
		case R.id.zhuangtaieditText:
			setStateActivity();
			break;
		// 相关项
		case R.id.xiangguanxiangeditText:
			setXiangGuanActivity();
			break;
		// 选择开始时间
		case R.id.dataLayout:
			// 弹出
			DateTimeUtil.initSelectTimePopuwindow(NewEventActivity.this,
					daoqiriqieditText, false);
			break;
		// 结束时间
		case R.id.btnData:
			// 弹出
			DateTimeUtil.initSelectTimePopuwindow(NewEventActivity.this,
					btnData, false);
			break;
		case R.id.daoqiriqieditText:
			final Button daoqiriqieditTexts = (Button) findViewById(R.id.daoqiriqieditText);// 到期日期
			// 弹出
			DateTimeUtil.initSelectTimePopuwindow(NewEventActivity.this,
					daoqiriqieditTexts, false);
			break;
		// 内容
		case R.id.beizhuedit:
			break;
		// 保存
		case R.id.newtaskbtn:
			getContent();
			break;
		default:
			break;
		}
	}

	String mTheme;
	String mFenPeiRen;
	String mStartTime;
	String mState;
	String mXinagGuan;
	String mContent;
	String mEndTime;
	String mJsonData;
	String mThemes = "主题不能为空";
	String mPersons = "被分配人不能为空";
	String mTimesa = "开始时间不能为空";
	String mEnTimes = "结束时间不能为空";
    String  mSaves = "正在保存...";
	public void getContent() {
		// 主题
		mTheme = zhutieditText.getText().toString().trim();
		// 被分配人名称
		mFenPeiRen = beifenpeireneditText.getText().toString().trim();
		// 被分配人id
		// userId
		// 开始时间
		mStartTime = mTime.getText().toString().trim();
		// 结束时间
		mEndTime = btnData.getText().toString().trim();
		// 状态
		mState = zhuangtaieditText.getText().toString().trim();
		// 相关项
		mXinagGuan = xiangguanxiangeditText.getText().toString().trim();
		// 内容
		mContent = beizhuedit.getText().toString().trim();

			if ("en".equals(mEns)) {
				 mThemes = "The topic can not be empty";
				 mPersons = "The assignee can not be empty";
				 mTimesa = "The start time can not be empty";
				 mEnTimes = "The end time can not be empty";
				 mSaves = "Saving...";
			}else{
				 mThemes = "主题不能为空";
				 mPersons = "被分配人不能为空";
				 mTimesa = "开始时间不能为空";
				 mEnTimes = "结束时间不能为空";
				 mSaves = "正在保存...";
			}
		if ("".equals(mTheme)) {
			Toast.makeText(this, mThemes, Toast.LENGTH_SHORT).show();
			return;
		} else if ("".equals(mFenPeiRen)) {
			Toast.makeText(this, mPersons, Toast.LENGTH_SHORT).show();
			return;
		} else if ("".equals(mStartTime)) {
			Toast.makeText(this, "mTimesa", Toast.LENGTH_SHORT).show();
			return;
		} else if ("".equals(mEndTime)) {
			Toast.makeText(this, mEnTimes, Toast.LENGTH_SHORT).show();
			return;
		}  else {
			setEtimeStime(mStartTime,mEndTime);

		}
	}

	// 把数据转换成json格式。用于上传服务端
	public void createJson() {
		JSONObject object = new JSONObject();
		if ("".equals(mTheme) & "".equals(userId) & "".equals(mStartTime)
				& "".equals(mEndTime) & "".equals(mState)
				& "".equals(mXinagGuan) & "".equals(mContent)) {
			return;
		}
		try {
			object.put("subject", mTheme);
			object.put("name", mTheme);
			object.put("belongtoid", userId);
			object.put("begintime", mStartTime);
			object.put("endtime", mEndTime);
//			object.put("status", mState);
			object.put("type", stateString);
			object.put("istask", "0");
			if (mXgx!=null&&mXgx.length() > 5) {
				object.put("relateid", mXgx);
				object.put("relateobj", mXgx.substring(0, 3));
			}
			object.put("remark", mContent);
			String mChange = "[" + object.toString() + "]";
			mJsonData = mChange;
			Log.d("转换数据-------------------------", mJsonData);
			System.out.println(object);
			// Log.d("/////////////////", object.toString());
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		sendDataHttp();
	}

	/**
	 * 保存数据
	 */
	public void sendDataHttp() {
		HttpUtils utils = new HttpUtils();
		RequestParams params = new RequestParams();
		params.addBodyParameter("binding", RunTimeManager.getInstance()
				.getServerBinding());
		params.addBodyParameter("serviceName", "insert");
		params.addBodyParameter("objectApiName", "Event");
		params.addBodyParameter("data", mJsonData);
		Log.d("事件url-------------------------", UrlManager.getInterfaceUrl()
				+ "?data=" + mJsonData + "&binding"
				+ RunTimeManager.getInstance().getServerBinding()
				+ "&serviceName=insert" + "&objectApiName=Event");
		utils.send(HttpMethod.POST, UrlManager.getInterfaceUrl(), params,
				new RequestCallBack<String>() {

					@Override
					public void onFailure(HttpException arg0, String arg1) {
						// TODO Auto-generated method stub
						showDialog.onDismissLoadingDialog();
						Log.d("保存接口失败-------------------------", arg1);
					}

					@Override
					public void onSuccess(ResponseInfo<String> arg0) {
						// TODO Auto-generated method stub
						showDialog.onDismissLoadingDialog();
						Log.d("保存接口成功-------------------------", arg0.result);
						SuccessBean mSucc = new Gson().fromJson(arg0.result,
								SuccessBean.class);
						if (mSucc.result) {
							if ("en".equals(mEns)) {
								Toast.makeText(NewEventActivity.this, "Saved successfully",
										Toast.LENGTH_SHORT).show();
							}else{
								Toast.makeText(NewEventActivity.this, "保存成功",
										Toast.LENGTH_SHORT).show();
							}

							finish();
						} else {
							if ("en".equals(mEns)) {
								Toast.makeText(NewEventActivity.this, "Save failed Please try again",
										Toast.LENGTH_SHORT).show();
							}else{
								Toast.makeText(NewEventActivity.this, "保存失败 请您重试",
										Toast.LENGTH_SHORT).show();
							}

						}
					}
				});
	}

	/**
	 * 被分配人
	 */
	public void setFenPeiActivity() {
		Intent intent = new Intent();

		intent.setClass(this, AtContaxtActivity_.class);

		startActivityForResult(intent, mPerson);

	}

	/**
	 * 选择类型
	 */
	public void setStateActivity() {
		Intent intent = new Intent();
		intent.setClass(this, NewStateActivity.class);
		intent.putExtra("m", "e");
		startActivityForResult(intent, mStateCode);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		if (null == data) {
			return;
		}
		switch (requestCode) {
		case 1:
			String mName = data.getStringExtra("name");
			if ("".equals(mName)) {
				return;
			}
			beifenpeireneditText.setText(mName);
			userId = data.getStringExtra("userId");
			break;
		case 2:
			String mNames = data.getStringExtra("nameName");
			if ("".equals(mNames)) {
				return;
			}
			stateString = data.getStringExtra("name");
			zhuangtaieditText.setText(mNames);

			break;
		case 10:
			mXgx = data.getStringExtra("AvA");
			String str1 = data.getStringExtra("AvAname");
			if ("".equals(str1)) {
				return;
			}
			xiangguanxiangeditText.setText(str1);
			break;
		default:
			break;
		}

		super.onActivityResult(requestCode, resultCode, data);
	}

	/**
	 * 相关项
	 */
	public void setXiangGuanActivity() {
		Intent intent = new Intent(this, NewRelatedActivity.class);
		intent.setClass(this, NewRelatedActivity.class);
		startActivityForResult(intent, 10);
	}
	/**
	 * 判断开始时间不能大于结束时间
	 */





	    public  int setEtimeStime(String DATE1, String DATE2) {
			String  mStart = DATE1.replace("-","").replace(":","").replace(" ","");
			String  mEnd = DATE2.replace("-","").replace(":","").replace(" ","");
			String s = mStart;
			String e = mEnd;
	        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm");
	        try {
	            Date dt1 = df.parse(DATE1);
	            Date dt2 = df.parse(DATE2);
	            if (Long.valueOf(mStart)>=Long.valueOf(mEnd)) {

						if ("en".equals(mEns)) {
							Toast.makeText(this, "The start time can not be greater than or equal to the end time", Toast.LENGTH_LONG).show();
						}else{
							Toast.makeText(this, "开始时间不能大于等于结束时间", Toast.LENGTH_LONG).show();
						}
						return 1;
//					}
//	                System.out.println("dt1 在dt2前");
//	                if ("en".equals(mEns)) {
//	                	 Toast.makeText(this, "The start time can not be greater than or equal to the end time", Toast.LENGTH_LONG).show();
//	        		}else{
//	        			 Toast.makeText(this, "开始时间不能大于等于结束时间", Toast.LENGTH_LONG).show();
//	        		}
//
//	                return 1;
	            } else if (Long.valueOf(mStart)<Long.valueOf(mEnd)) {

	             // 发送数据
	    			showDialog.onShowLoadingDialog(mSaves);
	    			createJson();
	                return -1;
	            } else if(Long.valueOf(mStart)==Long.valueOf(mEnd)){
	            	if ("en".equals(mEns)) {
	            		Toast.makeText(this, "The end time is later than the start time", Toast.LENGTH_LONG).show();
	        		}else{
	        			Toast.makeText(this, "结束时间须晚于开始时间", Toast.LENGTH_LONG).show();
	        		}

	            	 return 2;
	            }else {
	                return 0;
	            }
	        } catch (Exception exception) {
	            exception.printStackTrace();
	        }
	        return 0;
	}
}
